package thread;

/**
 * 有效的缩小同步范围可以在保证并发安全前提下提高并发效率
 * 同步块的应用
 */
public class SyncDemo2 {
    public static void main(String[] args) {
        Shop shop = new Shop();
        Shop shop1 = new Shop();
        Shop shop2 = new Shop();
//        Thread t1 = new Thread("翠花") {
//            public void run() {
//                shop.buy();
////                shop1.buy();
//            }
//        };
//        Thread t2 = new Thread("无颜祖") {
//            public void run() {
//                shop.buy();
////                shop2.buy();
//            }
//        };
        //简化代码，lambda表达式
//        Runnable r1 = ()->shop1.buy();
//        Thread t1 = new Thread(r1);

        //进一步简化:
//        Thread t1 = new Thread(()->shop1.buy());
        /*
            当lambda表达式只有一行代码时，可以简化为:
            ()->shop1.buy()
            ^^           ^^
             |---一致-----|
            如果此时lambda表达式的参数列表与这行代码调用的方法参数列表一致时
            可以简化为:方法引用的写法
            对象::方法名
            shop1::buy
         */
        Thread t1 = new Thread(shop1::buy);
        Thread t2 = new Thread(shop2::buy);
        t1.start();
        t2.start();
    }
}

class Shop {
    public void buy() {
        try {
            Thread t = Thread.currentThread();
            System.out.println(t.getName() + "正在挑衣服...");
            Thread.sleep(3000);
            synchronized (t) {
                System.out.println(t.getName() + "正在试衣服...");
                Thread.sleep(3000);
            }
            System.out.println(t.getName() + "结账走人");
        } catch (InterruptedException e) {
        }
    }
}
